<template>
  <el-drawer
    v-model="drawerVisible"
    :z-index="1000"
    :destroy-on-close="true"
    size="1000px"
    :title="`${drawerProps.title}`"
    :before-close="_colse"
  >
    <el-form
      ref="trainPlanFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="trainPlanForm"
      :hide-required-asterisk="drawerProps.isView"
      :inline="true"
    >
      <el-form-item label="方案名称" prop="planName">
        <el-input v-model="trainPlanForm.planName" placeholder="请填写方案名称" style="width: 300px" clearable></el-input>
      </el-form-item>

      <el-form-item label="适用装置" prop="deviceList">
        <el-select
          multiple
          clearable
          v-model="trainPlanForm.deviceList"
          placeholder="请选择适用装置"
          style="width: 300px"
          @change="_getStationNoList"
        >
          <el-option v-for="item in deviceSelList" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId" />
        </el-select>
      </el-form-item>
      <div class="handlerList" v-if="stationNoList?.length">
        <div class="handlerBar" v-for="(item, index) in trainPlanList" :key="item.id">
          <div class="handlerBar__header">
            <div class="stationNo">工位编号{{ item.stationNo }}：</div>
            <el-button type="primary" plain :icon="CirclePlus" @click="_addQuestionItem(index)">新增试题</el-button>
          </div>
          <div class="handlerBar__item" v-for="(child, childIdx) in item.questionList" :key="child.questionId">
            <el-icon class="delBtn" :size="20"><CircleClose @click="_delQuestionItem(index, childIdx)" /></el-icon>
            <div class="questionBar">
              <el-select
                class="questionType"
                v-model="child.questionType"
                clearable
                placeholder="请选择故障类型"
                style="width: 240px"
                @change="_setDataList($event, index, childIdx)"
              >
                <el-option v-for="val in questionType" :key="val.label" :label="val.label" :value="val.value" />
              </el-select>
            </div>
            <div class="questionList">
              <el-select
                class="dataName"
                v-model="child.dataName"
                clearable
                placeholder="请选择故障名称"
                style="width: 240px"
                :disabled="!child.dataList.length"
                @change="_setDataItemList($event, index, childIdx)"
              >
                <el-option
                  v-for="val in questionSelData[child.questionType]"
                  :key="val.dataName"
                  :label="val.dataName"
                  :value="val.dataName"
                />
              </el-select>
              <div class="questionItem" v-for="(val, idx) in child.dataList" :key="val.questionId">
                <div class="layoutForm" v-if="child.dataNameIdx === idx">
                  <div class="layoutItem" v-for="v in val.dataItemList" :key="v.itemId">
                    <div class="layoutItem__labName">{{ v.itemName }}</div>
                    <el-form-item class="layoutItem__con">
                      <el-select v-model="v.itemValue" v-if="v.itemType === 1" style="width: 200px">
                        <el-option :label="o.lable" :value="o.value" v-for="o in v.selectList" :key="o.value" />
                      </el-select>
                      <el-date-picker
                        style="width: 200px"
                        placeholder=""
                        :type="v.itemType === 7 ? 'date' : 'datetime'"
                        :format="v.itemType === 7 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
                        :value-format="v.itemType === 7 ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
                        v-model="v.itemValue"
                        v-else-if="v.itemType === 7 || v.itemType === 8"
                      />
                      <el-input v-model="v.itemValue" v-else></el-input>
                    </el-form-item>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="CabineDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { ResultData, TrainPlan } from "@/api/interface";
import { CirclePlus } from "@element-plus/icons-vue";
import { getCabinetSelList } from "@/api/modules/files1Manage/cabinet";
import { getQuestionSelList, getStationNoList, getTrainPlanDtl } from "@/api/modules/train1Manage/trainPlan";

const trainPlanForm: any = ref({
  planName: "",
  deviceList: []
});

const trainPlanList: any = ref([]);

const deviceSelList: any = ref([]);
const stationNoList: any = ref([]);
const questionSelData: any = ref([]);
const questionType: any = ref([]);

const rules = reactive({
  planName: [{ required: true, trigger: "blur", message: "请填写方案名称" }],
  deviceList: [{ required: true, trigger: "blur", message: "请选择适用装置" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<TrainPlan.ResTrainPlanList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  let stationList: any = [];
  drawerProps.value = params;
  drawerVisible.value = true;
  await getCabinetSelData();
  await getQuestionSelData();
  if (drawerProps.value.title === "编辑") {
    const { planId, planName, deviceList } = drawerProps.value.row;
    trainPlanForm.value.planId = planId;
    trainPlanForm.value.planName = planName;
    if (deviceList) {
      trainPlanForm.value.deviceList = deviceList.map((item: any) => {
        return item.deviceId;
      });
    }
    await _getStationNoList();
    const { result } = (await getTrainPlanDtl({ planId: trainPlanForm.value.planId })) as ResultData;
    result.stationList.forEach((item: any) => {
      item.questionList = item.questionList.map((val: any) => {
        questionSelData.value[val.objectStyle].forEach((obj: any, objIdx: number) => {
          if (obj.dataName === val.dataName) {
            val.dataNameIdx = objIdx;
          }

          if (obj.commandId === val.commandId) {
            obj.dataItemList = val.dataList;
          }
          obj.dataItemList.forEach((v: any) => {
            switch (v.itemType) {
              case 1:
                v.itemValue = v.defaultValue ?? "";
                console.log(v.selectList);
                if (v.selectList && v.selectList.length > 0) {
                  v.selectList.some((o: any) => {
                    if (o.isSelected) {
                      v.itemValue = o.value;
                      return false;
                    }
                  });
                }
                break;
              default:
                v.itemValue = v.defaultValue ?? "";
                break;
            }
          });
        });

        return {
          questionType: val.objectStyle.toString(),
          dataName: val.dataName,
          dataNameIdx: val.dataNameIdx,
          dataList: questionSelData.value[val.objectStyle]
        };
      });
      stationList.push({ stationNo: item.stationNo, questionList: item.questionList });
    });
    trainPlanList.value = stationList;
  }
};

// 提交数据（新增/编辑）
const trainPlanFormRef = ref<FormInstance>();

/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  trainPlanList.value = [];
  trainPlanForm.value = [];
  trainPlanFormRef.value && trainPlanFormRef.value.resetFields();
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  trainPlanFormRef.value!.validate(async valid => {
    if (!valid) return;
    let isReturn: boolean = false;
    interface stationItem {
      stationNo: string;
      questionList: {
        length: any;
        questionId: string;
        dataName: string;
        dataList: { itemId: string; itemValue: string }[];
      };
    }
    let stationList: stationItem[] = [];
    const ruleMap: Map<number, RegExp> = new Map([
      [
        2,
        /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      ],
      [
        3,
        /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(254|252|248|240|224|192|128|0)$/
      ],
      [4, /^(192\.168(\.(\d|([1-9]\d)|(1\d{2})|(2[0-4]\d)|(25[0-5]))){2})$/],
      [5, /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/],
      [6, /^([0-9a-fA-F]{2}(:|-)){5}[0-9a-fA-F]{2}$/],
      [9, /(^[+]{0,1}1[0-2]|[1-9])$/],
      [10, /^([+]{0,1}([0-5]?[0-9])|60)$/],
      [11, /^([+]{0,1}([0-5]?[0-9])|60)$/],
      [13, /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/],
      [14, /^[+]{0,1}[0-9]+(.[0-9]{1})?$/],
      [15, /^[+]{0,1}[0-9]+(.[0-9]{1})?$/]
    ]);
    isReturn = !trainPlanList.value.some((item: any) => {
      return item.questionList.length;
    });
    if (isReturn) {
      ElMessage.error(`请至少选择一道试题`);
      return false;
    }
    trainPlanList.value.forEach((item: any) => {
      let stationItem: any = {};
      if (item.questionList?.length) {
        if (isReturn) return false;
        stationItem.stationNo = item.stationNo;
        stationItem.questionList = [];
        item.questionList.forEach((child: any) => {
          if (isReturn) return false;
          if (child.dataList?.length) {
            if (!child.dataName) {
              ElMessage.error(`工位编号${item.stationNo}：请选择故障名称`);
              isReturn = true;
              return false;
            }
            child.dataList.forEach((val: any, idx: number) => {
              if (child.dataNameIdx === idx) {
                if (!isReturn) {
                  try {
                    val.dataItemList.forEach((v: any) => {
                      if (!v.itemValue && v.itemValue !== 0) {
                        ElMessage.error(`工位编号${item.stationNo}-${v.itemName}：输入值为空`);
                        isReturn = true;
                      }
                      const ruleItem: any = ruleMap.get(v?.itemType);
                      if (ruleMap.has(v.itemType) && !ruleItem.test(v.itemValue)) {
                        ElMessage.error(`工位编号${item.stationNo}-${v.itemName}：输入值格式不正确`);
                        isReturn = true;
                      }
                    });
                  } catch (err: any) {
                    console.log(err.message);
                  }
                }
                const dataList = val.dataItemList.map((v: any) => {
                  return {
                    itemId: v.itemId,
                    itemValue: v.itemValue
                  };
                });
                stationItem.questionList.push({ questionId: val.questionId, dataList });
                try {
                  if (isReturn) throw Error();
                } catch (err: any) {
                  console.log(err.message);
                }
              }
            });
          } else {
            ElMessage.error(`工位编号${item.stationNo}：请选择故障类型`);
            isReturn = true;
          }
        });
        stationList.push(stationItem);
      }
    });

    if (isReturn) return false;

    stationList.forEach((item, index) => {
      if (!item.questionList.length) {
        stationList = stationList.splice(index, 1);
      }
    });

    let paramsData = {
      stationList,
      ...trainPlanForm.value
    };

    paramsData.deviceList = JSON.parse(JSON.stringify(trainPlanForm.value.deviceList)).map((item: any) => {
      return {
        deviceId: item
      };
    });

    try {
      await drawerProps.value.api!(paramsData);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
      trainPlanForm.value = [];
      trainPlanList.value = [];
    } catch (error) {
      console.log(error);
    }
  });
};
/**
 * 获取装置选择列表
 */
const getCabinetSelData = async () => {
  const { result } = (await getCabinetSelList({
    pageNum: 1,
    pageSize: 10000
  })) as ResultData;
  deviceSelList.value = result.dataList;
};

const getQuestionSelData = async () => {
  const { result } = (await getQuestionSelList({})) as ResultData;
  Object.keys(result).forEach((item: any) => {
    console.log(item, typeof item);
    switch (item) {
      case "2":
        questionType.value[0] = { label: "线路故障", value: item };
        break;
      case "4":
        questionType.value[1] = { label: "采集终端故障", value: item };
        break;
      case "5":
        questionType.value[2] = { label: "电能表故障", value: item };
        break;
      default:
        break;
    }
  });
  questionSelData.value = result;
};

/**
 * 获取工位表号列表
 */
const _getStationNoList = async () => {
  const deviceList = trainPlanForm.value.deviceList.map((item: any) => {
    return {
      deviceId: item
    };
  });
  if (!deviceList.length) {
    stationNoList.value = [];
    return false;
  }

  const { dataList } = (await getStationNoList({ deviceList })) as ResultData;
  let trainPlanArr: any = [];
  dataList.forEach((item: any) => {
    trainPlanArr.push({ ...item, questionList: [] });
  });
  trainPlanArr.forEach((item: any) => {
    trainPlanList.value.forEach((val: any) => {
      if (item.stationNo === val.stationNo) {
        item.questionList = val.questionList;
      }
    });
  });

  trainPlanList.value = trainPlanArr;
  stationNoList.value = dataList;
};

/**
 * 增加培训方案子项
 */
const _addQuestionItem = (curIndex: number) => {
  trainPlanList.value[curIndex].questionList.push({ dataName: "", dataNameIdx: -1, dataList: [] });
};
/**
 * 删除培训方案子项
 */
const _delQuestionItem = (parentIndex: number, curIndex: number) => {
  trainPlanList.value[parentIndex].questionList.splice(curIndex, 1);
};

/**
 * 设置故障名称选项
 */
const _setDataList = (key: any, parentIndex: number, curIndex: number) => {
  const questionList = JSON.parse(JSON.stringify(questionSelData.value[key]));
  questionList.forEach((item: any) => {
    item.dataItemList.forEach((val: any) => {
      switch (val.itemType) {
        case 1:
          val.itemValue = val.defaultValue ?? "";
          if (val.selectList && val.selectList.length > 0) {
            val.selectList.some((v: any) => {
              if (v.isSelected) {
                val.itemValue = v.value;
                return false;
              }
            });
          }
          break;
        default:
          val.itemValue = val.defaultValue ?? "";
          break;
      }
    });
  });

  trainPlanList.value[parentIndex].questionList[curIndex].dataList = questionList;
};
/**
 * 设置故障子项
 */
const _setDataItemList = (key: any, parentIndex: number, curIndex: number) => {
  trainPlanList.value[parentIndex].questionList[curIndex].dataName = key;
  const dataNameIdx = trainPlanList.value[parentIndex].questionList[curIndex].dataList.findIndex((item: any) => {
    return item.dataName == key;
  });

  trainPlanList.value[parentIndex].questionList[curIndex].dataNameIdx = dataNameIdx;
};

defineExpose({
  acceptParams
});
</script>
<style lang="scss" scope>
.handlerList {
  padding: 0 30px 20px;
  .handlerBar {
    width: 100%;
    .handlerBar__header {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding: 20px 0;
      font-size: 14px;
    }
    .handlerBar__item {
      position: relative;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      width: 100%;
      padding: 10px 20px;
      margin-bottom: 20px;
      border: 1px solid #eeeeee;
      border-radius: 5px;
      .delBtn {
        position: absolute;
        top: -8px;
        right: -8px;
        color: var(--el-color-danger);
        cursor: pointer;
      }
      .questionBar {
        display: flex;
        flex: 1;
        align-items: center;
      }
      .questionList {
        display: flex;
        flex: 2;
        align-items: center;
        justify-content: space-between;
        .questionItem {
          display: flex;
          align-items: center;
          .layoutForm {
            flex: 1;
            .layoutItem {
              box-sizing: border-box;
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              margin-bottom: 10px;
              &:last-child {
                margin-bottom: 0;
              }
              .layoutItem__labName {
                box-sizing: border-box;
                width: 50%;
                height: 100%;
                padding: 10px;
                font-size: 14px;
                color: var(--el-input-text-color, var(--el-text-color-regular));
                text-align: center;
              }
              .layoutItem__con {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 50%;
                padding: 0 10px;
                margin: 0 auto;
                text-align: center;
                :deep(.el-form-item__content) {
                  justify-content: center;
                  width: 100%;
                }
              }
            }
          }
        }
      }
    }
    .handlerBar__item:last-child {
      margin-bottom: 0;
    }
  }
  .stationNo,
  .questionType {
    margin-right: 20px;
  }
}
</style>
